package com.lr.app.application;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.lr.falsework.common.tool.WebContainerTool;
import com.ws.commons.interfac.Result;
import com.ws.commons.interfac.ResultStatus;
import com.ws.commons.tool.StrTool;

@WebFilter(urlPatterns = { "/serv/*", "/sys/*" }, filterName = "authorityFilter")
public class AuthorityFilter implements Filter {

	private MultipartResolver multipartResolver = null;  
	public static ConfigurableApplicationContext applicationContext=null;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("loginFilter启动==================");
	}
  
	final Result UNAUTHORIZED_RESULT = new Result(
			new ResultStatus(HttpStatus.UNAUTHORIZED.value() + "", HttpStatus.UNAUTHORIZED.getReasonPhrase()));
	final Result UNAUTHORIZED_TIMEOUT_RESULT = new Result(
			new ResultStatus(HttpStatus.UNAUTHORIZED.value() + "", "会话过期"));

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest res = (HttpServletRequest) request;
		String token = WebContainerTool.getToken();
		if (StrTool.isEmpty(token)) {
			WebContainerTool.responseResult(UNAUTHORIZED_RESULT);  
		} else {
			MySession mySession = MySessionContext.getValidSession(token);  
			if (mySession == null) {
				WebContainerTool.responseResult(UNAUTHORIZED_TIMEOUT_RESULT);
			} else {  
				mySession.active(); 
				long sta = System.currentTimeMillis();
				String contentType = res.getContentType();
				if (StrTool.isNotEmpty(contentType) && contentType.contains("multipart/form-data")) {
					if (multipartResolver == null) {
						multipartResolver = applicationContext.getBean(MultipartResolver.class);
						if (multipartResolver == null) {
							multipartResolver = new CommonsMultipartResolver();
						}
					}
					request = multipartResolver.resolveMultipart(res);
				}
				chain.doFilter(request, response);
				long end = System.currentTimeMillis();
				System.out.println(res.getRequestURL() + "请求耗时：" + (end - sta) + "毫秒");
			}
		}
	}

	@Override
	public void destroy() {
		System.out.println("loginFilter销毁==================");
	}

}
